package com.example.hnvehicle.config;

import com.example.hnvehicle.bean.Result;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author heimi
 * @version 1.0
 * @description 处理器配置类
 * @date 2023/5/24 上午10:58
 */
@Configuration
public class AuthorizationProcessesConfig {

    @Resource
    private ObjectMapper objectMapper;  // 序列化器

    /**
     * @description 认证成功处理器
     * @author heimi
     * @date 2023/5/24 上午11:11
     */
    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
        return (request, response, authentication) -> {
            Object principal = authentication.getPrincipal();
            User user=(User)principal;
            String username = user.getUsername();
            Collection<GrantedAuthority> authorities = user.getAuthorities();
            List<GrantedAuthority> list = new ArrayList<>(authorities );
            GrantedAuthority authority=list.get(0);
            Result result;
            if("admin".equals(authority.getAuthority())){
               result = new Result(HttpServletResponse.SC_OK, true, username+",管理员");
            }else {
               result = new Result(HttpServletResponse.SC_OK, true, username+",普通用户");
            }
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json;charset=utf-8");
            String responseStr = objectMapper.writeValueAsString(result);
            PrintWriter writer = response.getWriter();
            writer.println(responseStr);
            writer.flush();
            System.out.println(result.getCode()+result.getData().toString()+result.getMessage());
        };
    }

    /**
     * @description 认证失败处理器
     * @author heimi
     * @date 2023/5/24 上午11:14
     */
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                Result result = new Result(HttpServletResponse.SC_FORBIDDEN, false, "认证错误");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.setContentType("application/json;charset=utf-8");
                String responseStr = objectMapper.writeValueAsString(result);
                PrintWriter writer = response.getWriter();
                writer.println(responseStr);
                writer.flush();
            }


        };
    }

    /**
     * @description 权限不足处理器
     * @author heimi
     * @date 2023/5/24 上午11:39
     */
    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return (request, response, accessDeniedException) -> {
            Result result = new Result(HttpServletResponse.SC_FORBIDDEN, false, "权限不足");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setContentType("application/json;charset=utf-8");
            String responseStr = objectMapper.writeValueAsString(result);
            PrintWriter writer = response.getWriter();
            writer.println(responseStr);
            writer.flush();
        };
    }
}